<template>
  <div>
    <el-form :model="user" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="用户名" prop="userName">
      <el-input type="text" v-model="user.userName" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="密码" prop="pwd">
      <el-input type="password" v-model="user.pwd" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="doLogin">提交</el-button>
    </el-form-item>
  </el-form>
  </div>
</template>

<script>
import { doLogin } from '_api'
export default {
  name: 'Login',
  data () {
    return {
      user: {
        userName: '',
        pwd: ''
      },
      rules: {
        userName: [
          {
            required: true,
            message: '用户名必填'
          }
        ],
        pwd: [
          {
            required: true,
            message: '密码必填'
          }
        ]
      }
    }
  },
  methods: {
    doLogin () {
      // 登录
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          // 提交
          doLogin(this.user).then(res => {
            if (res.data.code === 200) {
              // 缓存
              const { token, role, userInfo } = res.data.data
              localStorage.setItem('token', token)
              localStorage.setItem('role', role)
              localStorage.setItem('userInfo', JSON.stringify(userInfo))
              this.$store.commit('user/SET_USER', res.data.data)
              // 过滤侧边导航
              this.$store.commit('permission/FILTER_MENUS', role)
              this.$message({
                type: 'success',
                message: res.data.msg,
                duration: 1000,
                onClose: () => {
                  this.$router.replace('/')
                }
              })
            }
          })
        } else {
          // 验证失败
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
